package cn.itcast.n4_共享模型_管程;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

import static cn.itcast.util.Sleeper.sleep;

/**
 * <p>
 * Test40_ReentrantLock_可重入性
 * </p>
 *
 * @author flyduck
 * @since 2024-10-11
 */
@Slf4j(topic = "c.Test41_ReentrantLock_可打断")
public class Test41_ReentrantLock_可打断 {

    private static ReentrantLock reentrantLock = new ReentrantLock();

    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            try {
                //如果没有竞争，此方法就会获取lock对象的锁
                //如果竞争了，就会进入阻塞队列等待，可以被其他线程用interrupt去打断
                log.debug("尝试去获取锁");
                reentrantLock.lockInterruptibly();
                try {
                    log.debug("获取到锁了");
                }finally {
                    reentrantLock.unlock();
                }
            } catch (InterruptedException e) {
                log.debug("没有获取到锁");
                e.printStackTrace();
            }
        }, "t1");

        reentrantLock.lock();
        t1.start();

        sleep(1);
        log.debug("打断t1");
        t1.interrupt();


    }
}
